package com.mfoyou.agent.web.service.order;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.mfoyou.agent.common.OP.OrderComonOp;
import org.mfoyou.agent.common.dao.domain.HuawuIdcardInfo;
import org.mfoyou.agent.common.dao.domain.HuawuServiceComponent;
import org.mfoyou.agent.common.dao.domain.HuawuServiceCoupon;
import org.mfoyou.agent.common.dao.domain.HuawuServiceOrder;
import org.mfoyou.agent.common.dao.domain.HuawuServiceUserCoupon;
import org.mfoyou.agent.common.dao.domain.HuawuStoreInfo;
import org.mfoyou.agent.common.dao.domain.HuawuUser;
import org.mfoyou.agent.common.dao.domain.HuawuWorker;
import org.mfoyou.agent.common.dao.domain.HuawuYouzan;
import org.mfoyou.agent.common.dao.domain.MfoyouRegionCustom;
import org.mfoyou.agent.common.dao.domain.MfoyouStationMaster;
import org.mfoyou.agent.common.dao.mfoyou.domain.MfoyouGoodsOrder;
import org.mfoyou.agent.common.entity.MfoyouCommonUtil;
import org.mfoyou.agent.common.entity.MfoyouGoodsOrderEx;
import org.mfoyou.agent.common.entity.enums.GoodsOrderState;
import org.mfoyou.agent.common.entity.enums.MfoyouUserType;
import org.mfoyou.agent.common.entity.enums.OrderState;
import org.mfoyou.agent.common.entity.enums.OrderType;
import org.mfoyou.agent.common.entity.enums.PayType;
import org.mfoyou.agent.common.inf.IAccount;
import org.mfoyou.agent.common.inf.IGoodsOrder;
import org.mfoyou.agent.common.inf.IIdentity;
import org.mfoyou.agent.common.inf.IOrder;
import org.mfoyou.agent.common.inf.IOther;
import org.mfoyou.agent.common.inf.IPayment;
import org.mfoyou.agent.common.inf.IStatistics;
import org.mfoyou.agent.utils.common.ArrayListObject;
import org.mfoyou.agent.utils.common.GisUtils;
import org.mfoyou.agent.utils.common.Logger;
import org.mfoyou.agent.utils.json.JSONMaker;
import org.mfoyou.agent.utils.map.ReflectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mfoyou.agent.web.service.account.StoreAgentService;
import com.mfoyou.agent.web.service.common.GeoService;
import com.mfoyou.agent.web.service.session.SessionService;
import com.mfoyou.agent.web.service.thirdPart.AmapService;
import com.mfoyou.agent.web.service.thirdPart.XGPushSerivce;
import com.mfoyou.agent.web.utils.common.MfoyouPriceV2;
import com.mfoyou.agent.web.utils.common.PriceData;
import com.mfoyou.agent.web.utils.redis.RedisCacheManger;

/**
 * 订单 service 服务
 *
 * @author hzhang7
 */
@Service
public class ServiceOrderService {

    @Autowired
    AmapService amapService;
    @Autowired
    RedisCacheManger redisCacheManger;
    @Autowired
    IStatistics iStatistics;
    @Autowired
    IIdentity iIdentity;
    @Autowired
    IAccount iAccount;
    @Autowired
    IOrder iOrder;
    @Autowired
    IOther iOther;
    @Autowired
    SessionService sessionService;
    @Autowired
    GeoService geoService;
    @Autowired
    XGPushSerivce xgPushSerivce;
    @Autowired
    PaymentService paymentService;
    @Autowired
    OrderService orderService;
    @Autowired
    IGoodsOrder iGoodsOrder;
    @Autowired
    StoreAgentService storeAgentService;
    @Autowired
    OrderRunnerService orderRunnerService;
    @Autowired
    IPayment iPayment;
    public static final String SERVICE_ORDER_TIME1 = "wx:runner_push_data1";
    public static final String SERVICE_ORDER_TIME2 = "wx:runner_push_data2";
    Logger logger = Logger.getLogger(ServiceOrderService.class);

    public int checkMfoyouOrder(HuawuServiceOrder huawuServiceOrder, int mode) {
        String[] fileds = new String[]{"serviceOrderBespeak",
                "serviceOrderWeight", "serviceOrderDistance"};
        if (!ReflectUtil.checkField(huawuServiceOrder, fileds)) {
            return -96;
        }
        int orderType = huawuServiceOrder.getServiceOrderType();
        Double srcLat = huawuServiceOrder.getServiceOrderPickupAddressLat();
        Double srcLon = huawuServiceOrder.getServiceOrderPickupAddressLon();
        Double desLat = huawuServiceOrder.getServiceOrderDeliveryAddressLat();
        Double desLon = huawuServiceOrder.getServiceOrderDeliveryAddressLon();
        if (orderType != 4) {
            List<MfoyouRegionCustom> list = iOrder.getCustomRegionListByAgentId(huawuServiceOrder.getAgentId());
            Integer checkInside = orderService.getStationIdByLon(list, srcLat, srcLon, desLat, desLon);
            if (checkInside != null && checkInside.intValue() == -1) {
                return -3333;
            }
            logger.info(checkInside + "");
            huawuServiceOrder.setStationId(checkInside);
        }
        if (orderType == 1 || orderType == 2 || orderType == 3) {
            if (huawuServiceOrder.getServiceOrderDeliveryAddressLat() == null
                    || huawuServiceOrder.getServiceOrderDeliveryAddressLon() == null) {
                return -96;
            }
        }
        if (orderType == 1 || orderType == 2) {
            if (srcLat == null || huawuServiceOrder.getServiceOrderPickupAddressLon() == null) {
                return -96;
            }
        }
        if (huawuServiceOrder.getServiceOrderDeliveryAddressLat() != null
                && huawuServiceOrder.getServiceOrderDeliveryAddressLon() != null) {
            huawuServiceOrder.setServiceUserLat(huawuServiceOrder.getServiceOrderDeliveryAddressLat());
            huawuServiceOrder.setServiceUserLon(huawuServiceOrder.getServiceOrderDeliveryAddressLon());
        } else {
            huawuServiceOrder.setServiceUserLat(huawuServiceOrder.getServiceOrderPickupAddressLat());
            huawuServiceOrder.setServiceUserLon(huawuServiceOrder.getServiceOrderPickupAddressLon());
        }
        huawuServiceOrder.setServiceOrderId(null);
        huawuServiceOrder.setServiceOrderNumber("" + huawuServiceOrder.getServiceOrderType()
                + huawuServiceOrder.getServiceOrderSendUser() + System.currentTimeMillis());
        huawuServiceOrder.setServiceOrderPayAmount(0);
        huawuServiceOrder.setServiceOrderState(OrderState.emOpenOrder.getValue());
        if ((huawuServiceOrder.getServiceOrderBespeak() != 1)
                || huawuServiceOrder.getServiceOrderEffectTime() == null) {
            huawuServiceOrder.setServiceOrderEffectTime(new Date());
        }
        int distance = 0;
        if (srcLat != null && srcLon != null && desLat != null && desLon != null) {
            distance = (int) (1000 * GisUtils.distVincenty(srcLat, srcLon, desLat, desLon));
            if (huawuServiceOrder.getServiceOrderDistance() > distance) {
                distance = huawuServiceOrder.getServiceOrderDistance();
            } else {
                logger.error("distance=" + distance + ";mfoyouServiceOrder.getServiceOrderDistance()="
                        + huawuServiceOrder.getServiceOrderDistance());
                distance = amapService.getDistance(srcLat, srcLon, desLat, desLon);
            }
        } else {
            distance = huawuServiceOrder.getServiceOrderDistance();
        }
        if (huawuServiceOrder.getServiceOrderAttachAmount() == null
                || huawuServiceOrder.getServiceOrderAttachAmount() < 0) {
            huawuServiceOrder.setServiceOrderAttachAmount(0);
        }
        PriceData priceData = null;
        if (huawuServiceOrder.getServiceOrderSource() != null
                && huawuServiceOrder.getServiceOrderSource().intValue() == 1) {
            priceData = calOrderPriceStoreV2(huawuServiceOrder.getAgentId(), huawuServiceOrder.getServiceOrderWeight(),
                    distance, huawuServiceOrder.getServiceOrderHour(), huawuServiceOrder.getServiceOrderEffectTime());
        } else {
            priceData = calOrderPriceV2(huawuServiceOrder.getAgentId(), orderType,
                    huawuServiceOrder.getServiceOrderWeight(), distance, huawuServiceOrder.getServiceOrderHour(), huawuServiceOrder.getServiceTagName(),
                    huawuServiceOrder.getServiceOrderEffectTime(), huawuServiceOrder.getTouchId(), huawuServiceOrder.getServiceOrderTitle(),
                    huawuServiceOrder.getServiceOrderSendUser(), true);
        }
        if (priceData == null) {
            return -1;
        }
        huawuServiceOrder.setServiceOrderStartAmount(priceData.getServiceOrderStartAmount());
        huawuServiceOrder.setServiceOrderAmount(
                priceData.getServiceOrderAmount() + huawuServiceOrder.getServiceOrderAttachAmount());
        huawuServiceOrder.setCouponReduceMoney(priceData.getCoupon_reduce());
        huawuServiceOrder.setCouponText(priceData.getCouponText());
        huawuServiceOrder.setServiceOrderWeightAmount(priceData.getServiceOrderWeightAmount());
        huawuServiceOrder.setServiceOrderDistanceAmount(priceData.getServiceOrderDistanceAmount());
        return 0;
    }

    public PriceData calOrderPriceStoreV2(Integer agentId, Integer weight, Integer distance, Integer hour, Date time) {
        String key = "pricev2:" + agentId + weight + distance + time;
        String value = redisCacheManger.getValue(key);
        if (!(value == null || value.equals(""))) {
            PriceData priceData = JSON.parseObject(value, PriceData.class);
            return priceData;
        }
        MfoyouPriceV2 mfoyouPrice = storeAgentService.getServicePrice(agentId);
        PriceData priceData = mfoyouPrice.calPriceData(weight, distance, hour, time, 2);
        redisCacheManger.setValue(key, JSON.toJSONString(priceData), 60);
        logger.info(JSON.toJSONString(priceData) + "--->v2");
        return priceData;
    }

    /**
     * 订单费用计算
     *
     * @param agentId    代理商id
     * @param type       订单类型[帮我做, 帮我取, 帮我跑, 帮我买]
     * @param weight     重量
     * @param distance   距离
     * @param hour       时间
     * @param tagName    标签名称
     * @param dt         时间
     * @param touchId    优惠券id
     * @param typeName   优惠券名称 eg: "帮我做"
     * @param userId     用户id
     * @param isAddOrder controller 默认传入 false
     * @return
     */
    public PriceData calOrderPriceV2(int agentId, int type, Integer weight, Integer distance, Integer hour, String tagName,
                                     Date dt, Integer touchId, String typeName, Integer userId, boolean isAddOrder) {

        logger.info(String.format("ServiceOrderService.calOrderPriceV2"));
        // redis换成 key 拼接
        String key = "pricev2:" + agentId + type + weight + distance + hour + tagName + touchId + dt;
        // 从缓存获取计费规则
        String value = redisCacheManger.getValue(key);
        if (!(value == null || value.equals(""))) {
            PriceData priceData = JSON.parseObject(value, PriceData.class);
            return priceData;
        }
        MfoyouPriceV2 mfoyouPriceV2 = null;
        if (type < 5) {
            // 查询计费规则 json
            String priceinfo = iStatistics.getPriceInfo(agentId, type);
            // 获取计费规则实体类
            mfoyouPriceV2 = getBaseAmount(priceinfo, tagName, dt);
        } else {
            List<HuawuServiceComponent> serviceComponentByAgentId = iIdentity.getServiceComponentByAgentId(agentId, 1, type);
            if (serviceComponentByAgentId.size() == 0) return null;
            JSONObject parseObject = JSONObject.parseObject(serviceComponentByAgentId.get(0).getComponentPrice());
            JSONArray jsonArrayTime = parseObject.getJSONArray("allowTime");
            if (checkAllowTime(dt, jsonArrayTime)) {
                return null;
            }
            mfoyouPriceV2 = parseObject.getObject("data", MfoyouPriceV2.class);
        }
        if (mfoyouPriceV2 == null) {
            return null;
        }

        // 计算订单费用
        PriceData priceData = mfoyouPriceV2.calPriceData(weight, distance, hour, dt, type);
        logger.info(String.format("计算出的订单费用：[%s]", JSON.toJSONString(priceData)));
        if (touchId != null) {
            logger.info(String.format("使用了优惠券 touchId=[%s]", touchId));
            // 优惠券id不为空 - 检查优惠券
            checkTouchId(touchId, priceData, agentId, typeName);
        } else if (typeName != null) {
            logger.info(String.format("前段未使用优惠券 touchId=[%s], typeName=[%s], userId=[%s]", touchId, typeName, userId));
            // 优惠券名称 - 查询优惠券
            /*
            List<HuawuServiceCoupon> canUseCoupon = getCanUseCoupon(agentId, typeName, userId);
            logger.info(String.format("根据 typeName 等查询出优惠券  result=[%s]", JSON.toJSONString(canUseCoupon)));
            if (canUseCoupon != null && canUseCoupon.size() > 0 && !isAddOrder) {
                checkTouchId(canUseCoupon.get(0).getTouchId(), priceData, agentId, typeName);
            }
            */
        }
        logger.info(String.format("最终返回的订单费用对象: [%s]", JSON.toJSONString(priceData)));
        // 缓存到 redis
        redisCacheManger.setValue(key, JSON.toJSONString(priceData), 10);
        return priceData;
    }

    /**
     * 判断当前时间是否在再规则计费时间范围内
     *
     * @param dt            当前时间(也有可能是前端指定传递的时间, 为指定时间默认为当前时间)
     * @param jsonArrayTime 时间范围集合 {allowTime : [ {startTime: '', endTime: ''}]}
     * @return
     */
    private boolean checkAllowTime(Date dt, JSONArray jsonArrayTime) {
        if (jsonArrayTime != null) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dt);
            int time = calendar.get(Calendar.HOUR_OF_DAY) * 100 + calendar.get(Calendar.MINUTE);
            boolean isInTime = false;
            for (int i = 0; i < jsonArrayTime.size(); i++) {
                JSONObject jsonObject = jsonArrayTime.getJSONObject(i);
                int startTime = jsonObject.getIntValue("startTime");
                int endTime = jsonObject.getIntValue("endTime");
                boolean conditionOne = startTime < endTime && time > startTime && time < endTime;
                boolean conditionTwo = startTime > endTime && time < startTime && time > endTime;
                if (conditionOne || conditionTwo) {
                    isInTime = true;
                }
            }
            if (!isInTime) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检查优惠券
     *
     * @param touchId   优惠券id
     * @param priceData 订单计算对象 eg: { tagPrice: { priceData }}
     * @param agentId   代理商id
     * @param typeName  优惠券名称 eg: 帮我送
     */
    public void checkTouchId(Integer touchId, PriceData priceData, Integer agentId, String typeName) {
        if (typeName == null) return;
        Integer serviceOrderAmount = priceData.getServiceOrderAmount();
        if (touchId != null && touchId.intValue() != 0 && touchId.intValue() != -1) {

            // 查询优惠券
            HuawuServiceCoupon coupon = iOther.getCouponByTouchId(touchId, agentId);
            if (coupon == null) {
                String content = "优惠券不可用";
                priceData.setCouponText(content);
                return;
            }
            Integer useType = coupon.getUseType();
            if (useType == 2) {
                // 表示该优惠券可用于那种类型的优惠 eg: "帮我送,帮我取"
                String couponText = coupon.getCouponText();
                if (couponText == null) return;
                String[] types = couponText.split(",");
                // 判断 typeName 是否在优惠券所属优惠的类型中
                boolean checkStringInStrings = checkStringInStrings(typeName, types);
                if (!checkStringInStrings) {
                    String content = "优惠券此分类不可用";
                    priceData.setCouponText(content);
                    return;
                }
            }

            // 优惠券金额
            Integer reduceValue = coupon.getReduceValue();
            if (reduceValue < -100) return;
            Integer reduceMoney = reduceValue < 0 ?
                    serviceOrderAmount * (100 + reduceValue) / 100 :
                    serviceOrderAmount - reduceValue > 0 ? reduceValue : serviceOrderAmount - 1;
            priceData.setCoupon_reduce(reduceMoney);
            priceData.setTouchId(touchId);
            priceData.setCouponText(coupon.getCouponName() + "||" + reduceMoney);
        }
    }

    /**
     * 检查当前服务类型是否在在集合中
     *
     * @param typeName  当前服务类型
     * @param types 当前所有优惠券支持类型
     * @return
     */
    public boolean checkStringInStrings(String typeName, String[] types) {
        for (String type : types) {
            if (type.equals(typeName)) {
                return true;
            }
        }
        return false;
    }

    public PriceData calOrderPriceV2(int agentId, int type, Integer weight, Integer distance, Integer hour, Integer tagId, Date dt) {
        String key = "pricev2:" + agentId + type + weight + distance + tagId;
        String value = redisCacheManger.getValue(key);
        if (!(value == null || value.equals(""))) {
            PriceData priceData = JSON.parseObject(value, PriceData.class);
            return priceData;
        }
        String priceinfo = iStatistics.getPriceInfo(agentId, type);
        MfoyouPriceV2 mfoyouPriceV2 = getBaseAmount(priceinfo, tagId, dt);
        if (mfoyouPriceV2 == null) {
            return null;
        }
        PriceData priceData = mfoyouPriceV2.calPriceData(weight, distance, hour, dt, type);
        redisCacheManger.setValue(key, JSON.toJSONString(priceData), 60);
        return priceData;
    }

    /**
     * 获取基本费用
     *
     * @param priceInfo 规则json
     * @param tagId     标签id
     * @param dt
     * @return
     */
    private MfoyouPriceV2 getBaseAmount(String priceInfo, Integer tagId, Date dt) {
        if (priceInfo == null) {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(priceInfo);
        JSONArray jsonArrayTime = parseObject.getJSONArray("allowTime");
        if (checkAllowTime(dt, jsonArrayTime)) {
            return null;
        }

        // 获取规则列表集合
        JSONArray jsonArray = parseObject.getJSONArray("data");
        for (int i = 0, s = jsonArray.size(); i < s; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (tagId.equals(jsonObject.getInteger("tagId"))) {
                return jsonObject.getObject("tagPrice", MfoyouPriceV2.class);
            }
        }
        logger.info("没有相关tagid:" + tagId);
        return null;
    }

    /**
     * 获取基本费用
     *
     * @param priceInfo 规则json
     * @param tagName   标签名称
     * @param dt
     * @return
     */
    private MfoyouPriceV2 getBaseAmount(String priceInfo, String tagName, Date dt) {
        if (priceInfo == null) {
            return null;
        }
        JSONObject parseObject = JSONObject.parseObject(priceInfo);
        JSONArray jsonArrayTime = parseObject.getJSONArray("allowTime");
        if (checkAllowTime(dt, jsonArrayTime)) {
            return null;
        }

        // 获取规则列表集合

        JSONArray jsonArray = parseObject.getJSONArray("data");
        for (int i = 0, s = jsonArray.size(); i < s; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            // 精确匹配标签
            if ((jsonObject.getString("tagName")).equals(tagName)) {
                return jsonObject.getObject("tagPrice", MfoyouPriceV2.class);
            }


        }
        logger.info("没有相关tagName:" + tagName);
        return null;
    }

    /**
     * 添加订单
     *
     * @param huawuServiceOrder
     * @return
     */
    public HuawuServiceOrder addServiceOrder(HuawuServiceOrder huawuServiceOrder) {
        return iOrder.addServiceOrder(huawuServiceOrder);
    }

    public HuawuServiceOrder getServiceOrderInfo(Integer orderId) {
        return iOrder.getServiceOrderInfo(orderId);
    }

    public Boolean updateServiceOrderState(HuawuServiceOrder oldOrder, HuawuServiceOrder targetOrder,
                                           Integer opUserId) {
        if (oldOrder.getServiceOrderId() == null) {
            return false;
        }
        Boolean updateState = iOrder.updateServiceOrderState(oldOrder, targetOrder, opUserId);
        HuawuServiceOrder serviceOrderInfo = iOrder.getServiceOrderInfo(oldOrder.getServiceOrderId());
        if (serviceOrderInfo.getServiceOrderSource() == 1) {
            MfoyouGoodsOrder oldGoodsOrder = new MfoyouGoodsOrder();
            oldGoodsOrder.setOrderTransportId(serviceOrderInfo.getServiceOrderId());
            MfoyouGoodsOrder newGoodsOrder = new MfoyouGoodsOrder();
            newGoodsOrder.setOrderTransportState(oldOrder.getServiceOrderState());
            if (targetOrder.getServiceOrderState() == OrderState.emServiceStart.getValue()) {
                newGoodsOrder.setOrderState(GoodsOrderState.emBeginDelivery.getValue());
            } else if (targetOrder.getServiceOrderState() == OrderState.emServiceFinshTake.getValue()) {
                newGoodsOrder.setOrderState(GoodsOrderState.emFinshDelivery.getValue());
            } else if (targetOrder.getServiceOrderState() == OrderState.emServiceRunerFinsh.getValue()) {
                newGoodsOrder.setOrderState(GoodsOrderState.emStoreFinsh.getValue());
                oldOrder.setServiceOrderState(OrderState.emServiceRunerFinsh.getValue());
                targetOrder.setServiceOrderState(OrderState.emServiceUserFinsh.getValue());
                iOrder.updateServiceOrderState(oldOrder, targetOrder, opUserId);
                OrderComonOp.finshOrderV1(serviceOrderInfo, iIdentity, iOrder, iPayment);
            }
            int result = 0;
            if (targetOrder.getServiceOrderState().intValue() != OrderState.emRunerAccept.getValue()) {
                result = iGoodsOrder.updateGoodOrderV2(oldGoodsOrder, newGoodsOrder);
            } else {
                result = 2;
            }
            if (result == 0) {
                logger.error("订单更新状态失败到，服务订单状态是" + oldOrder.getServiceOrderState());
            }
        }
        return updateState;
    }

    public ArrayListObject<HuawuServiceOrder> getServiceOrderList(HuawuServiceOrder mfoyouServiceOrder, Integer pageId,
                                                                  Integer pageSize, Date startDate, Date endDate, List<Integer> state, Integer orderby) {

        return iOrder.getServiceOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, state, orderby);
    }

    public ArrayListObject<JSONObject> attachWorkUserInfo(ArrayListObject<HuawuServiceOrder> listObject,
                                                          String[] keys) {
        ArrayListObject<JSONObject> jsonObjects = new ArrayListObject<JSONObject>();
        List<Integer> workerids = listObject.stream()
                .map((huawuServiceOrder) -> huawuServiceOrder.getServiceOrderReceiveUser())
                .collect(Collectors.toList());
        Map<Integer, HuawuUser> mapUser = null;
        Map<Integer, HuawuWorker> mapworker = null;
        if (workerids.size() == 0) {
            mapworker = new HashMap<>();
            mapUser = new HashMap<>();
        } else {
            List<Integer> arrUser = new ArrayList<>();
            arrUser.addAll(workerids);
            mapworker = getMfoyouWorkerMap(arrUser);
            mapUser = userMapById(arrUser);
        }
        for (HuawuServiceOrder mfoyouEvaluate : listObject) {
            if (mfoyouEvaluate.getServiceOrderReceiveUser() != null)
                jsonObjects.add(JSONMaker.mergeJson(mfoyouEvaluate,
                        JSONMaker.mergeJson(mapUser.get(mfoyouEvaluate.getServiceOrderReceiveUser()),
                                mapworker.get(mfoyouEvaluate.getServiceOrderReceiveUser())),
                        keys));
            else
                jsonObjects.add(JSONMaker.mergeJson(mfoyouEvaluate, new JSONObject(), keys));
        }


        jsonObjects.setCurSize(listObject.getCurSize());
        jsonObjects.setPageId(listObject.getPageId());
        jsonObjects.setPageSize(listObject.getPageSize());
        jsonObjects.setTotalCount(listObject.getTotalCount());
        return jsonObjects;

    }

    private Map<Integer, HuawuWorker> getMfoyouWorkerMap(List<Integer> arrUser) {
        ArrayList<Integer> listState = new ArrayList<>();
        listState.add(OrderState.emRunerAccept.getValue());
        listState.add(OrderState.emServiceFinshPick.getValue());
        listState.add(OrderState.emServiceStart.getValue());
        Map<Integer, Integer> mfoyouServiceOrderCountMap = iOrder.getWorkerOrder(arrUser, listState, null, null);
        List<HuawuWorker> list = iIdentity.getMfoyouWorkerList(arrUser, null);
        Map<Integer, HuawuWorker> hashmap = new HashMap<>();
        list.stream().map((HuawuWorker huawuWorker) -> {
            Map<String, String> map = redisCacheManger.getMapValue("u:" + huawuWorker.getUserId());
            if (map != null) {
                if (map.get("lon") != null && map.get("lat") != null) {
                    huawuWorker.setWorkerLong(Double.parseDouble(map.get("lon")));
                    huawuWorker.setWorkerLat(Double.parseDouble(map.get("lat")));
                }
                if (huawuWorker.getWorkerName() == null)
                    huawuWorker.setWorkerName(map.get("userName"));
                if (huawuWorker.getWorkerName() == null) {
                    HuawuIdcardInfo idcardInfo = iAccount.getIdcardInfo(huawuWorker.getUserId());
                    if (idcardInfo != null) {
                        huawuWorker.setWorkerName(idcardInfo.getUserTrueName());
                    }
                }

            }
            huawuWorker.setWorkerOrderCount(mfoyouServiceOrderCountMap.get(huawuWorker.getUserId()));
            return huawuWorker;
        }).forEach((huawuWorker) -> hashmap.put(huawuWorker.getUserId(), huawuWorker));
        return hashmap;
    }

    public Map<Integer, HuawuUser> userMapById(List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return new HashMap<>();
        }
        List<HuawuUser> list = iAccount.userListById(ids);
        Map<Integer, HuawuUser> map = new HashMap<>();
        for (HuawuUser mfoyouUser : list) {

            map.put(mfoyouUser.getUserId(), mfoyouUser);
        }
        logger.info("get user list " + ids + "\n map = " + map);
        return map;
    }

    public List<HuawuServiceOrder> getServiceOrderListbyId(List<Integer> listId, List<Integer> listState,
                                                           List<Integer> workerIds) {
        return iOrder.getServiceOrderListbyId(listId, listState, workerIds);
    }

    public Integer getOrderCount(HuawuServiceOrder mfoyouServiceOrder, Date startDate, Date endDate,
                                 List<Integer> states) {
        return iOrder.getOrderCount(mfoyouServiceOrder, startDate, endDate, states);
    }

    public Boolean gainOrder(HttpServletRequest request, Integer runerId, Integer orderId) {
        HuawuWorker mfoyouWorkerInfo = iAccount.getWorkerInfo(runerId);
        HuawuServiceOrder oldOrder = new HuawuServiceOrder();
        oldOrder.setServiceOrderId(orderId);
        oldOrder.setServiceOrderState(OrderState.emPaySucess.getValue());
        oldOrder.setAgentId(mfoyouWorkerInfo.getAgentId());
        HuawuServiceOrder newOrder = new HuawuServiceOrder();
        newOrder.setServiceOrderState(OrderState.emRunerAccept.getValue());
        newOrder.setServiceOrderReceiveUser(runerId);
        // 计算提成金额
        HuawuServiceOrder mfoyouServiceOrder = getServiceOrderInfo(orderId);
        if (mfoyouServiceOrder.getStationId() != null) {
            if (mfoyouWorkerInfo.getStationId() == null || !mfoyouWorkerInfo.getStationId().equals(mfoyouServiceOrder.getStationId())) {
                return false;
            }
        }
        MfoyouStationMaster mfoyouStationMaster = iIdentity.getMfoyouStationInfo(mfoyouWorkerInfo.getStationId());
        MfoyouCommonUtil.calcOrderPercentage(mfoyouServiceOrder, mfoyouWorkerInfo.getWorkerFee(), mfoyouStationMaster, 1);
        newOrder.setServiceAgentAmount(mfoyouServiceOrder.getServiceAgentAmount());
        newOrder.setServiceStationAmount(mfoyouServiceOrder.getServiceStationAmount());
        newOrder.setStationId(mfoyouWorkerInfo.getStationId());
        newOrder.setServiceRunnerAmount(mfoyouServiceOrder.getServiceRunnerAmount());
        newOrder.setRunerPercent(mfoyouServiceOrder.getRunerPercent());
        newOrder.setStationPercent(mfoyouServiceOrder.getStationPercent());
        newOrder.setStationId(mfoyouWorkerInfo.getStationId());
        Boolean bRet = updateServiceOrderState(oldOrder, newOrder, sessionService.currentUserId(request));
        if (bRet) {
            if (mfoyouServiceOrder.getServiceOrderSource() == 1) { // 商品订单
                MfoyouGoodsOrder oldGoodsOrder = new MfoyouGoodsOrder();
                oldGoodsOrder.setOrderTransportId(orderId);
                MfoyouGoodsOrder newGoodsOrder = new MfoyouGoodsOrder();
                newGoodsOrder.setOrderState(GoodsOrderState.emAccect.getValue());
                newGoodsOrder.setOrderTransportState(OrderState.emRunerAccept.getValue());
                if (mfoyouWorkerInfo != null) {
                    newGoodsOrder.setOrderTransportRunerName(mfoyouWorkerInfo.getWorkerName());
                    newGoodsOrder.setOrderTransportRunerPhone(mfoyouWorkerInfo.getWorkerPhone());
                }
                int result = iGoodsOrder.updateGoodOrderV2(oldGoodsOrder, newGoodsOrder);
                if (result == 0) {
                    logger.error("订单更新状态失败");
                }
            }
            geoService.removeOrderPos("" + orderId);
            if (sessionService.currentUserId(request).equals(runerId)) {
                xgPushSerivce.pushOrderNoticeUser(null, orderId, 3, 101, "已接单");
                if (mfoyouServiceOrder.getServiceOrderEffectTime() != null) {
                    if (mfoyouServiceOrder.getServiceOrderBespeak() == 1)
                        redisCacheManger.hset(SERVICE_ORDER_TIME1, orderId + "",
                                runerId + ":" + mfoyouServiceOrder.getServiceOrderEffectTime().getTime() + ":" + orderId
                                        + ":" + mfoyouWorkerInfo.getAgentId());
                    else
                        redisCacheManger.hset(SERVICE_ORDER_TIME2, orderId + "", runerId + ":" + new Date().getTime()
                                + ":" + orderId + ":" + mfoyouWorkerInfo.getAgentId());
                }
            } else {
                xgPushSerivce.pushOrderNoticeUser(null, orderId, 3, 101, "订单已被接收");
            }
        }
        return bRet;
    }

    public Map<Integer, Integer> getEvaluateScoreCount(Integer agentId, Date startDate, Date endDate) {
        return iOrder.getEvaluateScoreCount(agentId, startDate, endDate);
    }

    public Map<Integer, Integer> getRunerEvaluateScoreCount(Integer userId, Date startDate, Date endDate) {
        return iOrder.getRunerEvaluateScoreCount(userId, startDate, endDate);
    }

    public Boolean revokeServiceOrder(Integer orderId, Integer userId, Integer payAmount, Integer orderState,
                                      Integer targetPayAmount, Integer targetState) {
        return iOrder.revokeServiceOrder(orderId, userId, payAmount, orderState, targetPayAmount, targetState);
    }

    public ArrayListObject<HuawuServiceOrder> getServiceOrderSquareList(HuawuServiceOrder mfoyouServiceOrder,
                                                                        Integer pageIndex, Integer pageSize, Date startDate, Date endDate, int usertype, List<Integer> states,
                                                                        long posHash) {
        return iOrder.getServiceOrderSquareList(mfoyouServiceOrder, pageIndex, pageSize, startDate, endDate, usertype,
                states, posHash);
    }

    public ArrayListObject<JSONObject> attachWorkerInfo(ArrayListObject<HuawuServiceOrder> listObject, String[] keys) {
        ArrayListObject<JSONObject> jsonObjects = new ArrayListObject<JSONObject>();
        List<Integer> userIds = new ArrayList<>();
        for (HuawuServiceOrder mfoyouEvaluate : listObject) {
            Integer workId = mfoyouEvaluate.getServiceOrderReceiveUser();
            if (workId == null)
                continue;
            userIds.add(mfoyouEvaluate.getServiceOrderReceiveUser());
        }
        Map<Integer, HuawuWorker> map = null;
        if (userIds.size() == 0) {
            map = new HashMap<>();
        } else {
            map = getMfoyouWorkerMap(userIds);
        }
        for (HuawuServiceOrder mfoyouEvaluate : listObject) {
            jsonObjects.add(
                    JSONMaker.mergeJson(mfoyouEvaluate, map.get(mfoyouEvaluate.getServiceOrderReceiveUser()), keys));
        }
        jsonObjects.setCurSize(listObject.getCurSize());
        jsonObjects.setPageId(listObject.getPageId());
        jsonObjects.setPageSize(listObject.getPageSize());
        jsonObjects.setTotalCount(listObject.getTotalCount());
        return jsonObjects;

    }

    public Map<String, Object> getAllOrderCount(Integer currentUserId, int type) {
        return iStatistics.getOrderCountAll(currentUserId, 0);
    }

    public ArrayListObject<HuawuServiceOrder> getAbnormalOrderList(HuawuServiceOrder mfoyouServiceOrder, Integer pageId,
                                                                   Integer pageSize, Date startDate, Date endDate, String type) {
        return iOrder.getAbnormalOrderList(mfoyouServiceOrder, pageId, pageSize, startDate, endDate, type);
    }

    /**
     * 新增服务订单
     *
     * @param mfoyouGoodsOrder
     * @param storeinfo
     * @param mode
     * @return
     */
    public int addServiceOrder(MfoyouGoodsOrderEx mfoyouGoodsOrder, HuawuStoreInfo storeinfo, int mode) {
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderSendUser(storeinfo.getStoreId());
        mfoyouServiceOrder.setServiceOrderNumber(mfoyouGoodsOrder.getOrderNumber());
        mfoyouServiceOrder.setServiceOrderSmallType(2);
        mfoyouServiceOrder.setServiceOrderType(2);
        mfoyouServiceOrder.setServiceOrderBespeak(mfoyouGoodsOrder.getOrderUserExpectTime() == null ? 0 : 1);
        mfoyouServiceOrder.setServiceOrderEffectTime(mfoyouGoodsOrder.getOrderUserExpectTime());
        mfoyouServiceOrder.setServiceTagId(-1);
        mfoyouServiceOrder.setServiceOrderDeliveryAddressLat(mfoyouGoodsOrder.getOrderUserLat());
        mfoyouServiceOrder.setServiceOrderDeliveryAddressLon(mfoyouGoodsOrder.getOrderUserLon());
        mfoyouServiceOrder.setServiceUserLat(mfoyouGoodsOrder.getOrderUserLat());
        mfoyouServiceOrder.setServiceUserLon(mfoyouGoodsOrder.getOrderUserLon());
        mfoyouServiceOrder.setServiceOrderPickupAddressLat(storeinfo.getStoreLocalLat());
        mfoyouServiceOrder.setServiceOrderPickupAddressLon(storeinfo.getStoreLocalLon());
        mfoyouServiceOrder.setServiceOrderAmount(mfoyouGoodsOrder.getOrderFreightAmount());
        mfoyouServiceOrder.setServiceOrderAttachAmount(0);
        mfoyouServiceOrder.setServiceOrderContent(mfoyouGoodsOrder.getOrderNote());
        mfoyouServiceOrder.setServiceOrderDeliveryAddress(mfoyouGoodsOrder.getOrderUserAddress());
        mfoyouServiceOrder.setServiceOrderDeliveryContactName(mfoyouGoodsOrder.getOrderUserName());
        mfoyouServiceOrder.setServiceOrderDeliveryContactNumber(mfoyouGoodsOrder.getOrderUserPhone());
        mfoyouServiceOrder.setServiceOrderDistance(mfoyouGoodsOrder.getOrderDistance());
        mfoyouServiceOrder.setServiceOrderPickupAddress(storeinfo.getStoreAddress());
        mfoyouServiceOrder.setServiceOrderPickupContactName(storeinfo.getStoreName());
        mfoyouServiceOrder.setServiceOrderPickupContactNumber(storeinfo.getStorePhone());
        mfoyouServiceOrder.setServiceOrderContent(makeContent(mfoyouGoodsOrder));
        mfoyouServiceOrder.setServiceOrderSourceId(mfoyouGoodsOrder.getOrderId());
        mfoyouServiceOrder.setServiceTagName("商城货物订单");
        mfoyouServiceOrder.setServiceOrderWeight(mfoyouGoodsOrder.getOrderWeight());
        mfoyouServiceOrder.setServiceOrderTitle("华悟云商商品送货");
        mfoyouServiceOrder.setAgentId(mfoyouGoodsOrder.getAreaAgentId());
        mfoyouServiceOrder.setServiceOrderSource(1);
        mfoyouServiceOrder.setServiceOrderBespeak(mfoyouGoodsOrder.getOrderBespeak());
        mfoyouServiceOrder.setServiceOrderEffectTime(mfoyouGoodsOrder.getExpectTime());
        mfoyouServiceOrder.setServiceOrderRemark(mfoyouGoodsOrder.getOrderMark());
        int ret = checkMfoyouOrder(mfoyouServiceOrder, mode);
        logger.info("计算结果：" + ret);
        mfoyouServiceOrder.setServiceOrderState(OrderState.emOpenOrder.getValue());
        if (ret != 0) {
            return ret;
        }
        int result = iOrder.addServiceOrderV1(mfoyouServiceOrder);
        logger.info("订单号" + result);
        if (result != 0) {
            // 自动付款
            if (!autoPayServiceOrder(mfoyouGoodsOrder, result)) {
                return -1002;
            }
            orderRunnerService.insertSeekAgentRunner(result);
            return result;
        }
        return -1002;
    }

    private Boolean autoPayServiceOrder(MfoyouGoodsOrderEx mfoyouGoodsOrder, Integer serviceId) {

        OrderInfo orderInfo = orderService.getOrderInfo(serviceId, OrderType.serviceOrder.getValue());
        if (orderInfo == null) {
            logger.info("orderInfo is null");
            return false;
        }
        if (!orderInfo.getOrderUserId().equals(mfoyouGoodsOrder.getStoreId())) {
            logger.error("user is error");
            return false;
        }
        if (orderInfo.getOrderState() >= OrderState.emPaySucess.getValue()) {
            return true;
        }
        int goodsOrderPayedAmount = mfoyouGoodsOrder.getOrderPayAmount(); // 实付
        int servicePayAmount = orderInfo.getOrderAmount() - orderInfo.getOrderPaidAmount();
        if (goodsOrderPayedAmount < servicePayAmount) {
            logger.error("运费钱不足");
            return false;
        }
        if (!orderService.payServiceTranspoetAmount(mfoyouGoodsOrder.getOrderId(), serviceId, servicePayAmount)) {
            return false;
        }
        orderService.payOrder(orderInfo.getOrderId(), OrderType.serviceOrder.getValue(), servicePayAmount,
                PayType.goodsOrder.getValue());

        paymentService.addStream(mfoyouGoodsOrder.getStoreId(), servicePayAmount, -1, serviceId,
                OrderType.serviceOrder.getValue(), PayType.goodsOrder.getValue(), PayType.serviceOrder.getValue(),
                "服务订单", MfoyouUserType.store.getValue());
        return true;
    }

    public String makeContent(MfoyouGoodsOrderEx mfoyouGoodsOrderEx) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ordernumber", mfoyouGoodsOrderEx.getOrderNumber());
        hashMap.put("detail", mfoyouGoodsOrderEx.getList());
        return JSON.toJSONString(hashMap);
    }

    /**
     * 获取优惠券列表
     *
     * @param agentId   代理商id
     * @param typeName  服务类型
     * @param userId    用户id
     *
     * @return
     */
    public List<HuawuServiceCoupon> getCanUseCoupon(Integer agentId, String typeName, Integer userId) {
        List<HuawuServiceCoupon> list = iOther.getCanUseCoupon(agentId, userId);
        if (typeName == null) {
            return list;
        }
        // 按照服务类型过滤优惠券结果：过滤条件 当前
        return list.stream().filter(huaWuServiceUserCoupon -> {
            String[] types = huaWuServiceUserCoupon.getCouponText().split(",");
            // useType=1 全平台通用;useType=2指定范围
            if (huaWuServiceUserCoupon.getUseType() == 2 && !checkStringInStrings(typeName, types)) {
                return false;
            }
            return true;
        }).collect(Collectors.toList());
    }

    public List<HuawuServiceCoupon> getCanUseCouponV2(Integer agentId, String typeName, Integer userId) {
        logger.info(String.format("获取可用优惠券列表 agentId=[%s];typeName=[%s];userId=[%s]", agentId, typeName, userId));
        List<HuawuServiceCoupon> list = iOther.getCanUseCoupon(agentId, userId);
        logger.info(String.format("最终获取到的优惠券列表数据 list=[%s]", JSON.toJSONString(list)));
        if (typeName == null) {
            return list;
        }
        Consumer<HuawuServiceCoupon> consumer = (HuawuServiceCoupon coupon) -> {
            if (coupon.getCouponText() != null || coupon.getCouponText() != "") {
                if (coupon.getUseType() == 2 && !checkStringInStrings(typeName, coupon.getCouponText().split(","))) {
                    coupon.setCanUsed(0);
                    coupon.setCouponDetail("该优惠券不能用于" + typeName);
                } else {
                    coupon.setCanUsed(1);
                }
            } else {
                coupon.setCanUsed(1);
            }

        };
        list.stream().forEach(consumer);
        list.stream().sorted(Comparator.comparing(HuawuServiceCoupon::getCanUsed).reversed()).collect(Collectors.toList());
        return list;
    }

    public int updateCoupon(HuawuServiceUserCoupon huawuServiceUserCoupon) {
        return iOther.updateCoupon(huawuServiceUserCoupon);
    }

    public int addYouzanOrder(JSONObject pushData, String number, HuawuYouzan huawuYouzan) {
        JSONObject msg = pushData.getJSONObject("response");
        JSONObject full_order_info = msg.getJSONObject("full_order_info");
        JSONObject address_info = full_order_info.getJSONObject("address_info");
        String address_extra = address_info.getString("self_fetch_info");
        if (address_extra == null || !address_extra.trim().equals("")) {
            return -2;
        }
        logger.info(pushData.toJSONString());
        address_extra = address_info.getString("address_extra");
        JSONObject parseObject = JSON.parseObject(address_extra);
        Double lon = parseObject.getDouble("lon");
        Double lat = parseObject.getDouble("lat");
        String address = amapService.getAddressByPos(lat, lon);
        String phone = address_info.getString("receiver_tel");
        String userName = address_info.getString("receiver_name");
        HuawuServiceOrder mfoyouServiceOrder = new HuawuServiceOrder();
        mfoyouServiceOrder.setServiceOrderSendUser(huawuYouzan.getUserId());
        mfoyouServiceOrder.setServiceOrderNumber(number);
        mfoyouServiceOrder.setServiceOrderSmallType(0);
        mfoyouServiceOrder.setServiceOrderType(-2);
        mfoyouServiceOrder.setServiceOrderBespeak(0);
        mfoyouServiceOrder.setServiceOrderEffectTime(new Date());
        mfoyouServiceOrder.setServiceTagId(-1);
        mfoyouServiceOrder.setServiceOrderDeliveryAddressLat(lat);
        mfoyouServiceOrder.setServiceOrderDeliveryAddressLon(lon);
        mfoyouServiceOrder.setServiceUserLat(lat);
        mfoyouServiceOrder.setServiceUserLon(lon);
        mfoyouServiceOrder.setServiceOrderPickupAddressLat(huawuYouzan.getStoreLat());
        mfoyouServiceOrder.setServiceOrderPickupAddressLon(huawuYouzan.getStoreLon());
        mfoyouServiceOrder.setServiceOrderAmount(0);
        mfoyouServiceOrder.setServiceOrderAttachAmount(0);
        mfoyouServiceOrder.setServiceOrderContent(pushData.getString("kdt_name"));
        mfoyouServiceOrder.setServiceOrderPickupContactName(huawuYouzan.getName());
        mfoyouServiceOrder.setServiceOrderPickupContactNumber(huawuYouzan.getStorePhone());
        mfoyouServiceOrder.setServiceOrderPickupAddress(huawuYouzan.getStoreAddress());
        mfoyouServiceOrder.setServiceOrderDeliveryContactName(userName);
        mfoyouServiceOrder.setServiceOrderDeliveryContactNumber(phone);
        mfoyouServiceOrder.setServiceOrderDeliveryAddress(address);
        mfoyouServiceOrder.setServiceOrderContent(full_order_info.getJSONArray("orders").toJSONString());
        mfoyouServiceOrder.setServiceOrderSourceId(-1);
        mfoyouServiceOrder.setServiceTagName("有赞货物订单");
        mfoyouServiceOrder.setServiceOrderWeight(0);
        mfoyouServiceOrder.setServiceOrderTitle("有赞商品送货");
        mfoyouServiceOrder.setAgentId(huawuYouzan.getAgentId());
        mfoyouServiceOrder.setServiceOrderSource(2);
        mfoyouServiceOrder.setServiceOrderRemark(null);
        int ret = checkYouzanOrder(mfoyouServiceOrder);
        logger.info("计算结果：" + ret);
        mfoyouServiceOrder.setServiceOrderState(OrderState.emOpenOrder.getValue());
        if (ret != 0) {
            return ret;
        }
        //有事务
        int result = iOrder.addYouzanServiceandPay(mfoyouServiceOrder);
        logger.info("订单号或者计算结果：center中-4：订单重复，-3钱不够，-5  订单添加失败：结果是" + result);
        if (result < 0) {
            return result;
        }
        orderService.payOrder(result, OrderType.serviceOrder.getValue(), mfoyouServiceOrder.getServiceOrderAmount(),
                PayType.wallet.getValue());
        paymentService.addStream(mfoyouServiceOrder.getServiceOrderReceiveUser(), mfoyouServiceOrder.getServiceOrderAmount(), -1,
                result, OrderType.serviceOrder.getValue(), PayType.goodsOrder.getValue(), PayType.serviceOrder.getValue(),
                "有赞服务订单", MfoyouUserType.store.getValue());
        return -1002;
    }

    /**
     * 计算有赞订单的价格
     *
     * @param mfoyouServiceOrder
     * @return
     */
    private int checkYouzanOrder(HuawuServiceOrder mfoyouServiceOrder) {
        mfoyouServiceOrder.setServiceOrderPayAmount(0);
        mfoyouServiceOrder.setServiceOrderState(OrderState.emOpenOrder.getValue());
        int distance = 0;
        Double srcLat = mfoyouServiceOrder.getServiceOrderDeliveryAddressLat();
        Double srcLon = mfoyouServiceOrder.getServiceOrderDeliveryAddressLon();
        Double userLat = mfoyouServiceOrder.getServiceOrderPickupAddressLat();
        Double userLon = mfoyouServiceOrder.getServiceOrderPickupAddressLon();
        if (srcLat != null && srcLon != null && userLat != null && userLon != null) {
            distance = amapService.getDistance(srcLat, srcLon, userLat, userLon);
        }
        PriceData priceData = null;
        priceData = calOrderPriceStoreV2(mfoyouServiceOrder.getAgentId(), mfoyouServiceOrder.getServiceOrderWeight(),
                distance, mfoyouServiceOrder.getServiceOrderHour(), mfoyouServiceOrder.getServiceOrderEffectTime());
        if (priceData == null) {
            return -1;
        }
        mfoyouServiceOrder.setServiceOrderDistance(distance);
        mfoyouServiceOrder.setServiceOrderStartAmount(priceData.getServiceOrderStartAmount());
        mfoyouServiceOrder.setServiceOrderAmount(
                priceData.getServiceOrderAmount() + mfoyouServiceOrder.getServiceOrderAttachAmount());
        mfoyouServiceOrder.setCouponReduceMoney(priceData.getCoupon_reduce());
        mfoyouServiceOrder.setCouponText(priceData.getCouponText());
        mfoyouServiceOrder.setServiceOrderWeightAmount(priceData.getServiceOrderWeightAmount());
        mfoyouServiceOrder.setServiceOrderDistanceAmount(priceData.getServiceOrderDistanceAmount());
        return 0;
    }

    public Boolean transferOrderToRuner(HttpServletRequest request, Integer runerId, Integer orderId) {
        HuawuWorker mfoyouWorkerInfo = iAccount.getWorkerInfo(runerId);
        HuawuServiceOrder oldOrder = new HuawuServiceOrder();
        oldOrder.setServiceOrderId(orderId);
        oldOrder.setAgentId(mfoyouWorkerInfo.getAgentId());
        HuawuServiceOrder newOrder = new HuawuServiceOrder();
        newOrder.setServiceOrderReceiveUser(runerId);
        newOrder.setAgentId(mfoyouWorkerInfo.getAgentId());
        // 计算提成金额
        HuawuServiceOrder mfoyouServiceOrder = getServiceOrderInfo(orderId);
        Integer oldRunnerId = mfoyouServiceOrder.getServiceOrderReceiveUser();
        oldOrder.setServiceOrderState(mfoyouServiceOrder.getServiceOrderState());
        if (mfoyouServiceOrder.getStationId() != null && mfoyouWorkerInfo.getStationId() != null &&
                !mfoyouWorkerInfo.getStationId().equals(mfoyouServiceOrder.getStationId())) {
            return false;
        }
        MfoyouStationMaster mfoyouStationMaster = iIdentity.getMfoyouStationInfo(mfoyouWorkerInfo.getStationId());
        MfoyouCommonUtil.calcOrderPercentage(mfoyouServiceOrder, mfoyouWorkerInfo.getWorkerFee(), mfoyouStationMaster, 2);
        newOrder.setServiceAgentAmount(mfoyouServiceOrder.getServiceAgentAmount());
        newOrder.setServiceStationAmount(mfoyouServiceOrder.getServiceStationAmount());
        newOrder.setStationId(mfoyouWorkerInfo.getStationId());
        newOrder.setRunerPercent(mfoyouServiceOrder.getRunerPercent());
        newOrder.setStationPercent(mfoyouServiceOrder.getStationPercent());
        newOrder.setStationId(mfoyouWorkerInfo.getStationId());
        Boolean bRet = updateServiceOrderStateForTransferOrder(oldOrder, newOrder, sessionService.currentUserId(request));
        String content = "管理员已转单成功，转单给" + mfoyouWorkerInfo.getWorkerPhone() + "(" + mfoyouWorkerInfo.getWorkerName() + ")";
        if (bRet) {
            if (mfoyouServiceOrder.getServiceOrderSource() == 1) { // 商品订单
                MfoyouGoodsOrder oldGoodsOrder = new MfoyouGoodsOrder();
                oldGoodsOrder.setOrderTransportId(orderId);
                MfoyouGoodsOrder newGoodsOrder = new MfoyouGoodsOrder();
                if (mfoyouWorkerInfo != null) {
                    newGoodsOrder.setOrderTransportRunerName(mfoyouWorkerInfo.getWorkerName());
                    newGoodsOrder.setOrderTransportRunerPhone(mfoyouWorkerInfo.getWorkerPhone());
                }
                int result = iGoodsOrder.updateGoodOrder(oldGoodsOrder, newGoodsOrder);
                if (result == 0) {
                    logger.error("订单更新状态失败");
                }
            }
            geoService.removeOrderPos("" + orderId);
            if (sessionService.currentUserId(request).equals(runerId)) {
                xgPushSerivce.transferCanclePushNoticeToUser(oldRunnerId, orderId, 1, 101, "取消", content);
                if (mfoyouServiceOrder.getServiceOrderEffectTime() != null) {
                    if (mfoyouServiceOrder.getServiceOrderBespeak() == 1)
                        redisCacheManger.hset(SERVICE_ORDER_TIME1, orderId + "",
                                runerId + ":" + mfoyouServiceOrder.getServiceOrderEffectTime().getTime() + ":" + orderId
                                        + ":" + mfoyouWorkerInfo.getAgentId());
                    else
                        redisCacheManger.hset(SERVICE_ORDER_TIME2, orderId + "", runerId + ":" + new Date().getTime()
                                + ":" + orderId + ":" + mfoyouWorkerInfo.getAgentId());
                }
            } else {
                xgPushSerivce.transferCanclePushNoticeToUser(oldRunnerId, orderId, 1, 101, "取消", content);
            }
        }
        return bRet;
    }

    public Boolean updateServiceOrderStateForTransferOrder(HuawuServiceOrder oldOrder, HuawuServiceOrder targetOrder,
                                                           Integer opUserId) {
        if (oldOrder.getServiceOrderId() == null) {
            return false;
        }
        Boolean updateState = iOrder.updateServiceOrderStateForTransferOrder(oldOrder, targetOrder, opUserId);
        return updateState;
    }
}
